/*
 * A Gneral purpose java based Genome Library created by Susanta Tewari.
 * Copyright is protected. Contact Susanta Tewari at <statsusant@yahoo.com>
 */

package genomemap.data;

import genomemap.data.Clone;
import genomemap.data.DataSource;
import genomemap.data.PDataSource;

import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

/**
 *
 * @author Susanta Tewari <stewari@yahoo.com>
 */
public class ClonePool {

    /**
     * @concern This might lead to memory problems:
     *  Map<ChID,Map<CloneOrder,Clone>>
     */
    private final Map<Integer, Map<Integer, Clone>> masterCloneMap = new Hashtable<>();

    /**
     * @throws RuntimeException
     * @param ch_id
     * @param cloneOrder
     */
    public Clone getClone(int ch_id, int cloneOrder) {

        Map<Integer, Clone> cloneMap = masterCloneMap.get(ch_id);

        if (cloneMap == null) {


            // load data for ch_id
            PDataSource pData           = DataSource.getPDataSource(ch_id);
            Collection<Clone> clones    = pData.getCloneSet();
            Map<Integer, Clone> tempMap = new Hashtable<>();

            for (Iterator<Clone> it = clones.iterator(); it.hasNext(); ) {

                Clone clone = it.next();

                tempMap.put(new Integer(clone.getOrder()), clone);
            }

            masterCloneMap.put(new Integer(ch_id), tempMap);


            // set data in the map
            cloneMap = masterCloneMap.get(ch_id);
        }

        if (cloneMap == null) {

            throw new RuntimeException("Clone Data for Chromosome- " + ch_id
                                       + "can not be loaded.");
        }

        return cloneMap.get(cloneOrder);
    }
}
